package com.iweb.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @autor jay
 * @data 2020/12/22
 * @desc 处理文件上传
 */
@WebServlet(name="UploadServlet1",urlPatterns = {"/servlet/doUpload1"})
public class UploadServlet1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String uploadPath = req.getServletContext().getRealPath("upload/");
        System.out.println("#######:" + uploadPath);
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(req);
                for (FileItem item : fileItems) {
                    // 普通表单字段
                    if (item.isFormField()) {
                        String productName = item.getFieldName();
                        out.println("商品名称：" + item.getString("utf-8"));
                    } else { // 文件字段
                        // 获取文件名称
                        String fileName = item.getName();
                        File tempFile = new File(fileName);
                        File saveFile = new File(uploadPath, tempFile.getName());
                        item.write(saveFile);
                        out.println("图片" + fileName +
                                "上传成功");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            out.println("当前表单不包含文件！");
        }
    }
}